package ec.atreasure.com.core.net.callback;

import android.content.Context;
import android.os.Handler;


import ec.atreasure.com.core.ui.AtreasureLoader;
import ec.atreasure.com.core.ui.LoaderStyle;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Description :网络请求回调函数业务逻辑类
 * Created by wangjin on 2019/6/23.
 * Job number：
 * Phone ：18301070822
 * Email： 120182051@qq.com
 * Person in charge : 汪渝栋
 * Leader：
 */
public class RequestCallbacks implements Callback<String> {

    private final IRequest iRequest;

    private final ISuccess iSuccess;

    private final IError iError;

    private final IFailure iFailure;

    private final LoaderStyle loaderStyle;

    private final Context context;

    private final Handler handler = new Handler();

    public RequestCallbacks(IRequest iRequest, ISuccess iSuccess,
                            IError iError, IFailure iFailure,
                            LoaderStyle loaderStyle, Context context) {
        this.iRequest = iRequest;
        this.iSuccess = iSuccess;
        this.iError = iError;
        this.iFailure = iFailure;
        this.loaderStyle = loaderStyle;
        this.context = context;
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        //成功
        if (response.isSuccessful()) {
            if (call.isExecuted()) {
                if (iSuccess != null) {
                    iSuccess.onSuccess(response.body());
                }
            }
        }
        //出错
        else {
            if (iError != null) {
                iError.onError(response.code(), response.message());
            }
        }

        onRequestFinish();
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        if (iFailure != null) {
            iFailure.onFaild();
        }

        if (iRequest != null) {
            iRequest.onEndRequest();
        }

        onRequestFinish();
    }

    /**
     * 请求结束关闭dialog过度动画
     */
    private void onRequestFinish() {
        if (loaderStyle != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AtreasureLoader.stopLoading();
                }
            },2000);
        }
    }
}
